<?php

function login($payload)
{
    logfile('<login>');
    $number = $payload->number;
    $passwd = $payload->passwd;
    $res = verify($number, $passwd);
    if ($res) {
        $output = getSingleData($number);
        $datatype = json_decode(file_get_contents('./data.conf.json'));
        return array('status' => 'success', 'security_data' => $res, 'basic_data' => $output['b'], 'extention_data' => $output['e'], 'data_conf' => $datatype);
    } else {
        return array('status' => 'failed');
    }
}

function verify($number, $passwd)
{
    logfile('<verifyUser>');
    $sql = "SELECT name,clientName,number,adminPIMS FROM oprec_security_data WHERE number = {$number} AND passwd='{$passwd}'";
    $res = exec_sql($sql);
    if ($res) {
        return $res;
    } else {
        return false;
    }
}

function getSingleData($number)
{
    logfile('<getSingleData>');
    $sql = "SELECT * FROM oprec_security_data WHERE number = {$number}";
    $b_data = exec_sql($sql);
    $sql = "SELECT recNumber,itemTitle,itemValue,timeStamp,status FROM pims_extention_data WHERE number = {$number} AND status > 7 ORDER BY recNumber DESC";
    $e_data = exec_sql($sql);
    return array('b' => $b_data, 'e' => $e_data);
}

function updateSingleData($payload, $verify)
{
    logfile('<updateSingleData>');
    $content = $payload->content;
    $number = $payload->login_data->number;
    $passwd = $payload->login_data->passwd;
    $security_data = verify($number, $passwd);
    if (!$security_data) {
        return false;
    } elseif ($security_data[0]['number'] != $content->number && $security_data[0]['adminPIMS'] != 1) {
        return false;
    }
    $status_old = 0;
    $status_new = 9;
    $remark = '未知情况修改';
    //if verify in need and user is not admin
    if ($verify && $security_data[0]['adminPIMS'] != 1) {
        $status_old = 7;
        $status_new = 8;
    }

    // status code :
    // 0 : discard with verified
    // 1 : discard without verified
    // 2 : refused by admin
    // 4 : dispose due import
    // 7 : being discard
    // 8 : being verified
    // 9 : verified by admin

    $timeStamp = getTimeStamp();
    $sql = "UPDATE pims_extention_data SET status = 1 WHERE number = {$content->number} AND itemTitle = '{$content->itemTitle}' AND status = 8";
    exec_sql($sql);
    $sql = "UPDATE pims_extention_data SET status = {$status_old} WHERE number = {$content->number} AND itemTitle = '{$content->itemTitle}' AND status = 9";
    exec_sql($sql);
    $sql = "INSERT INTO pims_extention_data VALUES (null, '{$content->clientName}',{$content->number},'{$content->itemTitle}','{$content->itemValue}',{$timeStamp},{$status_new})";
    exec_sql($sql);

    // record admin operation
    if ($security_data[0]['clientName'] == $content->clientName) {
        $remark = '由本人通过编辑器修改';
    } elseif ($security_data[0]['adminPIMS'] >= 1 || !$verify) {
        $remark = '由管理员通过编辑器修改';
    }
    // saveMsg($operator, $member, $number, $action, $items, $remark)
    $items =  array('title' => $content->itemTitle, 'value' => $content->itemValue, 'value_old' => $content->value_old);
    saveMsg($security_data[0]['clientName'], $content->clientName, $content->number, 'modify', $items, $remark);
    return true;
}

function getVerifyList($payload)
{
    logfile('<getVerifyList>');
    $security_data = verify($payload->number, $payload->passwd);
    // logfile(print_r($security_data, true));
    if ($security_data && $security_data[0]['adminPIMS'] >= 1) {
        $sql = "SELECT * FROM pims_extention_data WHERE status = 8";
        $content = exec_sql($sql);
        if (!$content) {
            return;
        }
        //logfile(print_r($content,true));
        $value_old = array();
        foreach ($content as $item) {
            $val = getSingleExtentionDataValue($item['number'], $item['itemTitle'], 7);
            if ($val) {
                array_push($value_old, $val['itemValue']);
            } else {
                array_push($value_old, '...');
            }
        }
        if (count($value_old) == 0) {
            $value_old = null;
        }

        return json_encode(array('result' => 'success', 'content' => $content, 'discard' => $value_old));
    } else {
        return json_encode(array('result' => 'unauthorized', 'content' => null));
    }
}

function getSingleExtentionDataValue($number, $itemTitle, $status)
{
    logfile('<getSingleExtentionDataValue>');
    $sql = "SELECT itemValue FROM pims_extention_data WHERE number={$number} AND itemTitle = '{$itemTitle}' AND status = {$status}";
    $value = exec_sql($sql);
    return $value[0];
}

function operateRequest($payload, $yes)
{
    logfile('<operateRequest>');
    $security_data = verify($payload->login_data->number, $payload->login_data->passwd);
    if ($security_data && $security_data[0]['adminPIMS'] >= 1) {
        $operate = '审核拒绝';
        $status_old = 9;
        $status_new = 2;
        if ($yes) {
            $operate = '审核通过';
            $status_old = 0;
            $status_new = 9;
        }
        $number = $payload->content->number;
        $user_clientName = $payload->content->clientName;
        $itemTitle = $payload->content->itemTitle;
        $value_new = $payload->content->itemValue;
        $value_old = $payload->value_old;
        $freetext = $payload->freetext;
        $time = getTimeStamp();
        $sql = "UPDATE pims_extention_data SET status = {$status_old} WHERE number = {$number} AND itemTitle = '{$itemTitle}' AND status = 7";
        exec_sql($sql);
        $sql = "UPDATE pims_extention_data SET status = {$status_new} WHERE number = {$number} AND itemTitle = '{$itemTitle}' AND status = 8";
        exec_sql($sql);
        //new method
        saveMsg($security_data[0]['clientName'], $user_clientName, $number, $operate, [['title' => $itemTitle, 'value' => $value_new, 'value_old' => $value_old]], $freetext);
        return true;
    } else {
        return false;
    }
}

function modifypasswd($payload)
{
    logfile('<modifypasswd>');
    $security_data = verify($payload->login_data->number, $payload->login_data->passwd);
    if ($security_data) {
        $sql = "UPDATE oprec_security_data SET passwd = '{$payload->passwd_new}' WHERE number = {$payload->login_data->number}";
        exec_sql($sql);
        saveMsg($security_data[0]['clientName'], $security_data[0]['clientName'], $payload->login_data->number, 'passwd', [['title' => 'passwd', 'value' => $payload->passwd_new]], 'modified passowrd by self');
    }
}

function resetpasswd($payload)
{
    logfile('<resetpasswd>');
    $security_data = verify($payload->login_data->number, $payload->login_data->passwd);
    if ($security_data && $security_data[0]['adminPIMS'] >= 1) {
        $sql = "UPDATE oprec_security_data SET passwd = 'appapp' WHERE number = {$payload->content->number}";
        exec_sql($sql);
        $remark = 'reset passwd by admin';
        saveMsg($security_data[0]['clientName'], $payload->number, $payload->clientName, 'resetpasswd', [['title' => 'passwd', 'value' => 'cdapp']], $remark);
    }
}

function importData($payload)
{
    logfile('<importData>');
    //verify if is admin
    $security_data = verify($payload->login_data->number, $payload->login_data->passwd);
    if ($security_data && $security_data[0]['adminPIMS'] >= 9) {
        $time_start = getTimeStamp();
        $del_user = [];
        $count = 0;
        // removed basic_data
        foreach ($payload->operate_data->to_delete->basic_data as $d) {
            array_push($del_user, $d->number);
            // true delete
            /*
            $sql="DELETE FROM oprec_security_data WHERE number = {$d->number}";
            exec_sql($sql);
            $sql="DELETE FROM oprec_security_data WHERE number = {$d->number}";
            exec_sql($sql);
            $sql="DELETE FROM pims_extention_data WHERE number = {$d->number}";
            exec_sql($sql);
             */
            // not true delete
            $sql = "UPDATE oprec_security_data SET passwd = '' WHERE number = {$d->number}";
            exec_sql($sql);
            $count++;
            $sql = "UPDATE pims_extention_data SET status = 4 WHERE number = {$d->number} AND itemTitle = '{$d->itemTitle}'";
            exec_sql($sql);
            $count++;
        }
        // removed extention_data
        foreach ($payload->operate_data->to_delete->extention_data as $d) {
            if (!in_array($d->number, $del_user)) {
                // $sql="DELETE FROM pims_extention_data WHERE number = {$d->number}";
                $sql = "UPDATE pims_extention_data SET status = 0 WHERE number = {$d->number} AND itemTitle = '{$d->itemTitle}'";
                exec_sql($sql);
                $count++;
            }
        }
        // modified basic_data
        foreach ($payload->operate_data->to_update->basic_data as $d) {
            $sql = "UPDATE oprec_security_data SET sex = '{$d->sex}', birth_date = '{$d->birth_date}', id_number = '{$d->id_number}', nation = '{$d->nation}' WHERE number = {$d->number}";
            exec_sql($sql);
            $count++;
        }
        // modified extention_data
        foreach ($payload->operate_data->to_update->extention_data as $d) {
            $sql = "UPDATE pims_extention_data SET status = 0 WHERE number = {$d->number} AND itemTitle = '{$d->itemTitle}'";
            exec_sql($sql);
            $count++;
            $sql = "INSERT INTO pims_extention_data VALUES (null, '{$d->clientName}',{$d->number},'{$d->itemTitle}','{$d->itemValue}',{$time_start},9)";
            exec_sql($sql);
            $count++;
        }
        // added basic_data
        foreach ($payload->operate_data->to_insert->basic_data as $d) {
            $sql = "INSERT INTO oprec_security_data VALUES({$d->serial_number}, '{$d->name}', '{$d->clientName}', {$d->number}, '{$d->sex}', '{$d->birth_date}', '{$d->id_number}', '{$d->nation}')";
            exec_sql($sql);
            $count++;
            $sql = "INSERT INTO oprec_security_data VALUES('{$d->name}', '{$d->clientName}', {$d->number}, 'cdapp', '[]', 0, 0, 0)";
            exec_sql($sql);
            $count++;
        }
        // added extention_data
        foreach ($payload->operate_data->to_insert->extention_data as $d) {
            $sql = "INSERT INTO pims_extention_data VALUES (null, '{$d->clientName}', {$d->number}, '{$d->itemTitle}', '{$d->itemValue}', {$time_start}, 9)";
            exec_sql($sql);
            $count++;
        }
        return array('result' => 'success', 'detail' => array('count' => $count, 'endurance' => (getTimeStamp() - $time_start)));
    }
    return array('result' => 'failed', "detail" => null);
}

function exportData($payload)
{
    //verify if is admin
    $security_data = verify($payload->login_data->number, $payload->login_data->passwd);
    if ($security_data && $security_data[0]['adminPIMS'] >= 1) {
        $sql = "SELECT * FROM oprec_security_data WHERE disposed = 0 ORDER BY CONVERT(clientName USING gbk) ASC";
        $data_b = exec_sql($sql);
        $sql = "SELECT * FROM pims_extention_data WHERE status = 9 OR status = 7";
        $data_e = exec_sql($sql);
        return array('result' => 'success', 'content' => array('basic_data' => $data_b, 'extention_data' => $data_e));
    }
    return array('result' => 'success', 'content' => null);
}

function getStuff($payload)
{
    //verify if is admin
    $security_data = verify($payload->login_data->number, $payload->login_data->passwd);
    if ($security_data && $security_data[0]['adminPIMS'] >= 1) {
        $sql = "SELECT clientName, number FROM oprec_security_data WHERE disposed = 0 ORDER BY CONVERT(clientName USING gbk) ASC";
        // $sql = "SELECT clientName, number FROM oprec_security_data ORDER BY CONVERT(clientName USING gbk) ASC";
        $data = exec_sql($sql);
        return array('result' => 'success', 'content' => $data);
    }
}

function modifySingleItem($payload)
{
    // status code :
    // 0 : discard with verified
    // 1 : discard without verified
    // 2 : refused by admin
    // 4 : dispose due import
    // 7 : being discard
    // 8 : being verified
    // 9 : verified by admin
    $security_data = verify($payload->login_data->number, $payload->login_data->passwd);
    if ($security_data) {
        $remark = '由本人通过编辑器修改';
        $operate = '申请修改';
        $time = getTimeStamp();
        $c = $payload->content;
        if ($security_data[0]['adminPIMS'] >= 1) {
            //admin operate
            $sql = "UPDATE pims_extention_data SET status = 0 WHERE number = {$c->number} AND itemTitle = '{$c->itemTitle}' AND status = 9";
            exec_sql($sql);
            $sql = "INSERT INTO pims_extention_data VALUES (null, '{$c->clientName}',{$c->number},'{$c->itemTitle}','{$c->itemValue}',{$time},9)";
            exec_sql($sql);
            $remark = '由管理员通过编辑器修改';
            $operate = '修改信息';
        } else {
            //user operate
            $sql = "UPDATE pims_extention_data SET status = 1 WHERE number = {$c->number} AND itemTitle = '{$c->itemTitle}' AND status = 8";
            exec_sql($sql);
            $sql = "UPDATE pims_extention_data SET status = 7 WHERE number = {$c->number} AND itemTitle = '{$c->itemTitle}' AND status = 9";
            exec_sql($sql);
            $sql = "INSERT INTO pims_extention_data VALUES (null, '{$c->clientName}',{$c->number},'{$c->itemTitle}','{$c->itemValue}',{$time},8)";
            exec_sql($sql);
        }
        $value_old = getSingleExtentionDataValue($c->number, $c->itemTitle, 9);
        if (!$value_old) $value_old = getSingleExtentionDataValue($c->number, $c->itemTitle, 8);
        saveMsg($security_data[0]['clientName'], $c->clientName, $c->number, $operate, [['title' => $c->itemTitle, 'value' => $c->itemValue, 'value_old' => $value_old]], $remark);
        return array('result' => 'success');
    }
    return array('result' => 'failed');
}

function deleteSingleItem($payload)
{
    $security_data = verify($payload->login_data->number, $payload->login_data->passwd);
    if ($security_data && $security_data[0]['adminPIMS'] >= 1) {
        $c = $payload->content;
        $remark = '由管理员通过编辑器删除信息';
        $sql = "UPDATE pims_extention_data SET status = 0 WHERE number = {$c->number} AND itemTitle = '{$c->itemTitle}' AND status = 9";
        exec_sql($sql);
        $value_old = getSingleExtentionDataValue($c->number, $c->itemTitle, 9);
        saveMsg($security_data[0]['clientName'], $c->clientName, $c->number, '删除信息', [['title' => $c->itemTitle, 'value' => '', 'value_old' => $value_old]], $remark);
        return array('result' => 'success');
    }
    return array('result' => 'failed');
}

function insertSingleItem($payload)
{
    $security_data = verify($payload->login_data->number, $payload->login_data->passwd);
    if ($security_data) {
        $time = getTimeStamp();
        $c = $payload->content;
        $remark = null;
        if ($security_data[0]['adminPIMS'] >= 1) {
            //admin operate
            $sql = "INSERT INTO pims_extention_data VALUES (null, '{$c->clientName}',{$c->number},'{$c->itemTitle}','{$c->itemValue}',{$time},9)";
            exec_sql($sql);
            $remark = '由管理员通过编辑器添加信息';
        } else {
            //user operate
            $sql = "INSERT INTO pims_extention_data VALUES (null, '{$c->clientName}',{$c->number},'{$c->itemTitle}','{$c->itemValue}',{$time},8)";
            exec_sql($sql);
            $remark = '由本人通过编辑器添加信息';
        }
        saveMsg($security_data[0]['clientName'], $c->clientName, $c->number, '添加信息', [['title' => $c->itemTitle, 'value' => $c->itemValue, 'value_old' => '']], $remark);
        return array('result' => 'success');
    }
    return array('result' => 'failed');
}

function batchModify($payload)
{
    $security_data = verify($payload->login_data->number, $payload->login_data->passwd);
    if ($security_data && $security_data[0]['adminPIMS'] >= 1) {
        $d = $payload->content;
        $time = getTimeStamp();
        //itemTitle in ...
        $itemarr = array();
        foreach ($d->items as $v) {
            array_push($itemarr, "'{$v->title}'");
        }
        $itemstr = join(', ', $itemarr);
        //number in ...
        $idarr = array();
        foreach ($d->users as $v) {
            array_push($idarr, "{$v->id}");
        }
        $idstr = join(', ', $idarr);
        $sql1 = "UPDATE pims_extention_data SET status = 0 WHERE number IN ({$idstr}) AND itemTitle IN ({$itemstr}) AND status > 6";
        exec_sql($sql1);
        //insert values
        $valuesarr = array();
        foreach ($d->items as $i) {
            foreach ($d->users as $u) {
                array_push($valuesarr, "(null,'{$u->name}',{$u->id},'{$i->title}','{$i->value}',$time,9)");
                // saveMsg($operator, $member, $number, $action, $items, $remark)
                saveMsg($security_data[0]['clientName'], $u->name, $u->id, '批量修改', [['title' => $i->title, 'value' => $i->value, 'value_old' => '']], '由管理员批量操作');
            }
        }
        $valuesstr = join(', ', $valuesarr);
        $sql2 = "INSERT INTO pims_extention_data VALUES {$valuesstr}";
        exec_sql($sql2);
        return array('result' => 'success', 'content' => [$sql1, $sql2]);
    }
    return array('result' => 'failed', 'content' => null);
}

function getOperateLog($payload)
{
    $security_data = verify($payload->login_data->number, $payload->login_data->passwd);
    if ($security_data && $security_data[0]['adminPIMS'] >= 1) {
        // $sql = "SELECT * FROM pims_operation_log WHERE action = 'approve' OR action = 'refuse'";
        $sql = "SELECT * FROM pims_operation_log ORDER BY time DESC";
        $content = exec_sql($sql);
        return array('result' => 'success', 'content' => array_chunk($content, 100));
    }
    return array('result' => 'success', 'content' => null);
}

function saveMsg($operator, $member, $number, $action, $items, $remark)
{
    /*
    operator : name of operator
    action : modify / approval / refusal / import / batch
    member : name of data operated
    number : number of member
    items : record data changes e.g. [{title, value, value_old}]
    remark : remark info
    time : timestamp with micro second
     */
    $time = getTimeStamp();
    $items_json = json_encode($items, JSON_UNESCAPED_UNICODE);
    $sql = "INSERT INTO pims_operation_log VALUES (null, '{$operator}','{$member}',{$number},'{$action}','{$items_json}','{$remark}',{$time})";
    exec_sql($sql);
}

function getTimeStamp()
{
    list($msec, $sec) = explode(' ', microtime());
    $microtime = (float) sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $microtime;
}
